using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PocketPals.Models;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using System.IO; // 添加 System.IO 命名空间
using System.Text.Json; // 添加 System.Text.Json 命名空间
using System; // 添加 System 命名空间

namespace PocketPals.Controllers
{
    // 添加一个简单的类来存储凭据
    internal class UserCredentials
    {
        public string Username { get; set; } = string.Empty;
        public string Password { get; set; } = string.Empty; // 实际应用中密码应加密存储
    }

    public class AuthController : Controller
    {
        private readonly string _credentialsFilePath; // 存储凭据文件路径

        // 构造函数中初始化文件路径和检查/创建文件
        public AuthController(ILogger<AuthController> logger = null)
        {
            _logger = logger;
            // 定义凭据文件路径（在程序运行目录下）
            _credentialsFilePath = Path.Combine(AppContext.BaseDirectory, "credentials.json");
            EnsureCredentialsFileExists(); // 确保文件存在
        }

        // 检查或创建凭据文件的方法
        private void EnsureCredentialsFileExists()
        {
            if (!System.IO.File.Exists(_credentialsFilePath))
            {
                _logger?.LogInformation($"Credentials file not found at {_credentialsFilePath}. Creating default file.");
                var defaultCredentials = new UserCredentials
                {
                    Username = "admin", // 默认用户名
                    Password = "password"  // 默认密码 (!!! 极不安全，仅供演示 !!!)
                };
                try
                {
                    string jsonString = JsonSerializer.Serialize(defaultCredentials, new JsonSerializerOptions { WriteIndented = true });
                    System.IO.File.WriteAllText(_credentialsFilePath, jsonString);
                    _logger?.LogInformation($"Default credentials file created successfully at {_credentialsFilePath}.");
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex, $"Failed to create credentials file at {_credentialsFilePath}.");
                    // 处理文件创建失败的情况，例如抛出异常或记录更详细的错误
                }
            }
            else
            {
                 _logger?.LogInformation($"Credentials file found at {_credentialsFilePath}.");
            }
        }


        // GET: /Auth/Login
        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            // EnsureCredentialsFileExists(); // 移到构造函数中，避免每次GET都检查
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        // POST: /Auth/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                UserCredentials? storedCredentials = null;
                try
                {
                    // 从文件加载凭据
                    if (System.IO.File.Exists(_credentialsFilePath))
                    {
                        string jsonString = System.IO.File.ReadAllText(_credentialsFilePath);
                        storedCredentials = JsonSerializer.Deserialize<UserCredentials>(jsonString);
                    }
                }
                catch (Exception ex)
                {
                     _logger?.LogError(ex, $"Error reading or deserializing credentials file at {_credentialsFilePath}.");
                     ModelState.AddModelError(string.Empty, "登录服务暂时不可用，请稍后再试。");
                     return View(model);
                }


                // 检查凭据是否加载成功以及是否匹配
                if (storedCredentials != null &&
                    model.Username.Equals(storedCredentials.Username, StringComparison.OrdinalIgnoreCase) &&
                    model.Password == storedCredentials.Password) // !!! 实际应用中应比较密码哈希值 !!!
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, model.Username),
                        // 可以添加其他声明，例如角色
                        // new Claim(ClaimTypes.Role, "Administrator"),
                    };

                    var claimsIdentity = new ClaimsIdentity(
                        claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    var authProperties = new AuthenticationProperties
                    {
                        IsPersistent = model.RememberMe,
                    };

                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity),
                        authProperties);

                    _logger?.LogInformation($"User {model.Username} logged in at {DateTime.UtcNow}.");

                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "无效的用户名或密码。"); // 更通用的错误消息
                    return View(model);
                }
            }

            // 如果执行到这里，说明模型验证失败，重新显示表单
            return View(model);
        }

        // POST: /Auth/Logout
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            _logger?.LogInformation($"User logged out at {DateTime.UtcNow}."); // 可选日志记录
            return RedirectToAction("Index", "Home"); // 或者重定向到登录页
        }

        // GET: /Auth/AccessDenied
        [AllowAnonymous]
        public IActionResult AccessDenied()
        {
            return View();
        }

        private IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                // 默认重定向到余额页面
                return RedirectToAction(nameof(BalanceController.Index), "Balance");
            }
        }

        // 可选：添加 ILogger 用于记录日志
        private readonly ILogger<AuthController> _logger;

        // 移除之前的构造函数，使用上面修改后的构造函数
        // public AuthController(ILogger<AuthController> logger = null) // 使 logger 可选，以便在没有配置 DI 时也能工作
        // {
        //     _logger = logger;
        // }
    }
}